
import React, { useEffect, useState } from 'react';
import LoginPage from './pages/LoginPage';
import { AuthProvider } from './contexts/AuthContext';
import { IonReactRouter } from '@ionic/react-router';
import {
  IonApp,
  IonSplitPane,
  IonRouterOutlet,
  setupIonicReact,
  IonTabs,
  IonTabBar,
  IonTabButton,
  IonIcon,
  IonLabel
} from '@ionic/react';
import { Route, Redirect } from 'react-router-dom';
import { useHistory } from 'react-router-dom';


import Sidebar from './components/Sidebar';
import HomePage from './pages/HomePage';
import ProfilePage from './pages/ProfilePage';
import SettingsPage from './pages/SettingsPage';
import NotificationsPage from './pages/NotificationsPage';
import MessagesPage from './pages/MessagesPage';
import HelpPage from './pages/HelpPage';
import FavoritesPage from './pages/FavoritesPage';
import RegisterPage from './pages/RegisterPage';
import SchedulePage from './planq/schedule/SchedulePage';
import { Capacitor } from '@capacitor/core';


/* Core CSS required for Ionic components to work properly */
import '@ionic/react/css/core.css';

/* Basic CSS for apps built with Ionic */
import '@ionic/react/css/normalize.css';
import '@ionic/react/css/structure.css';
import '@ionic/react/css/typography.css';

/* Optional CSS utils that can be commented out */
import '@ionic/react/css/padding.css';
import '@ionic/react/css/float-elements.css';
import '@ionic/react/css/text-alignment.css';
import '@ionic/react/css/text-transformation.css';
import '@ionic/react/css/flex-utils.css';
import '@ionic/react/css/display.css';



import {
  home,
  person,
  settings,
  notifications,
  mail,
  helpCircle,
  star
} from 'ionicons/icons';
import { foodRoute, homeRoute, planTempalteRoute, reportRoute, scheduleRoute, sportRoute, todoRoute, waterRoute, weightRoute } from './route/route';
import ReportPage from './planq/ReportPage';
import PlanPage from './planq/PlanPage';
import TodoPage from './planq/TodoPage';
import FoodPage from './planq/food/FoodPage';
import WeightPage from './planq/WeightPage';
import SportPage from './planq/SportPage';
import WaterPage from './planq/WaterPage';
import SqliteService from './services/sqliteService';
import DbVersionService from './services/dbVersionService';
import StorageService from './services/storageService';
import AppInitializer from './components/AppInitializer/AppInitializer';

setupIonicReact();


export const platform = Capacitor.getPlatform();

// Singleton Services
export const SqliteServiceContext = React.createContext(SqliteService);
export const DbVersionServiceContext = React.createContext(DbVersionService);
export const StorageServiceContext = React.createContext(new StorageService(SqliteService, DbVersionService));


const App: React.FC = () => {

  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const history = useHistory();

  /* callback function after login sucess */
  const handleLoginSuccess = (token: String) => {
    setIsAuthenticated(true)
    history.push('/home');
  }
  return (
    <SqliteServiceContext.Provider value={SqliteService}>
      <DbVersionServiceContext.Provider value={DbVersionService}>
        <StorageServiceContext.Provider value={new StorageService(SqliteService, DbVersionService)}>
          <AppInitializer>
            <IonApp>
              <AuthProvider>
                <IonReactRouter>
                  {!isAuthenticated ? (
                    // <LoginApp handleLoginSuccess={handleLoginSuccess} />
                    <MainApp />
                  ) : (
                    <MainApp />
                  )}
                </IonReactRouter>
              </AuthProvider>
            </IonApp>
          </AppInitializer>
        </StorageServiceContext.Provider>
      </DbVersionServiceContext.Provider>
    </SqliteServiceContext.Provider>
  )
}

interface LoginAppProps {
  handleLoginSuccess: (token: string) => void;
}

const LoginApp: React.FC<LoginAppProps> = ({ handleLoginSuccess }) => (
  <IonRouterOutlet id="main-content">
    <Route exact path="/login">
      <LoginPage onLoginSuccess={handleLoginSuccess} />
    </Route>
    <Route exact path="/register" component={RegisterPage} />
    <Redirect exact from="/" to="/login" />
    <Redirect to="/login" />
  </IonRouterOutlet>
)


const MainApp: React.FC = () => {
  const [isDarkMode, setIsDarkMode] = useState(false);
  const toggleDarkMode = () => {
    setIsDarkMode(!isDarkMode);
    document.body.classList.toggle('dark', !isDarkMode);
  };


  return (
    <IonSplitPane contentId="main-content" when="md">
      {/* 侧滑菜单 - 在平板/桌面显示 */}
      <Sidebar
        isDarkMode={isDarkMode}
        toggleDarkMode={toggleDarkMode}
      />

      <IonRouterOutlet id="main-content">
        {/* 标签页布局管理主内容 */}
        <Route path="/">
          <IonTabs>
            <IonRouterOutlet>
              <Route exact path="/home" component={HomePage} />
              <Route exact path="/profile" component={ProfilePage} />
              <Route exact path="/settings" component={SettingsPage} />
              <Route exact path="/notifications" component={NotificationsPage} />
              <Route exact path="/messages" component={MessagesPage} />
              <Route exact path="/help" component={HelpPage} />
              <Route exact path="/schedules" component={SchedulePage} />

              <Route exact path={reportRoute} component={ReportPage} />
              <Route exact path={planTempalteRoute} component={PlanPage} />
              <Route exact path={todoRoute} component={TodoPage} />
              <Route exact path={foodRoute} component={FoodPage} />
              <Route exact path={weightRoute} component={WeightPage} />
              <Route exact path={sportRoute} component={SportPage} />
              <Route exact path={waterRoute} component={WaterPage} />
              <Redirect to={scheduleRoute} />
            </IonRouterOutlet>


            {/* 底部导航栏 - 在移动设备显示 */}
            <IonTabBar slot="bottom" className="bottom-tab-bar">
              <IonTabButton tab="home" href="/home">
                <IonIcon icon={home} />
                <IonLabel>首页</IonLabel>
              </IonTabButton>

              <IonTabButton tab="favorites" href="/schedules">
                <IonIcon icon={star} />
                <IonLabel>日程</IonLabel>
              </IonTabButton>

              <IonTabButton tab="messages" href="/messages">
                <IonIcon icon={mail} />
                <IonLabel>消息</IonLabel>
              </IonTabButton>

              <IonTabButton tab="profile" href="/profile">
                <IonIcon icon={person} />
                <IonLabel>我的</IonLabel>
              </IonTabButton>
            </IonTabBar>
          </IonTabs>
        </Route>
      </IonRouterOutlet>
    </IonSplitPane>
  )
}


export default App